package com.nand.blockdemo.ui.feedback;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.HttpParams;
import com.nand.blockdemo.R;
import com.nand.blockdemo.adapter.FeekEditAdapter;
import com.nand.blockdemo.bean.FeedbackTypeBean;
import com.nand.blockdemo.bean.ModulePageBean;
import com.nand.blockdemo.constant.URL;
import com.nand.blockdemo.ui.dialog.PhotoDialog;
import com.nand.blockdemo.util.CommonUtil;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.GlideEngine;
import com.nand.library.base.utils.ObjectUtils;
import com.nand.library.base.utils.SpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FeekEditActivity extends BaseActivity {

    // 单选组
    private List<CheckBox> radios = new ArrayList<>();
    private String checkBoxV;

    private EditText mDescribe, mTheme;
    private TextView mModular, mType, mContacts;
    private OptionsPickerView typePicker, mPagePicker;      //todo  部门人员选择功能 contactsPicker,
    private List<String> typeList = new ArrayList<>();

    private int userId;

    //部门人员数据     //todo  部门人员选择功能
//    private List<String> departList = new ArrayList<>();
//    private List<List<String>> staffList = new ArrayList<>();
//    private int options;
//    private String departOid;
//    private String userOid;
//    private List<DepartmentBean> depList = new ArrayList<>();

    //模块界面数据
    private List<String> modelList = new ArrayList<>();
    private List<List<String>> pageList = new ArrayList<>();
    private int modelOptions;
    private String pageName;
    private String modularName;
    private RecyclerView mRecyclerView;

    private List<String> photos = new ArrayList<>();//图片数据
    private FeekEditAdapter mAdapter;
    private String add = "add";
    private int photoNum = 6;//需要上传的数量
    private int requestCode = 2;
    private List<ModulePageBean> modulePageList;

    private boolean pendingCollapseKeyword = false;
    private View focusedView;

    @Override
    protected boolean isActionBar() {
        return true;
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_feek_edit;
    }

    @Override
    protected void initView() {
        mActionBar().setCenterText("意见反馈");

        mModular = findViewById(R.id.tv_modular);
        mType = findViewById(R.id.tv_type);
        mDescribe = findViewById(R.id.et_describe);
        mTheme = findViewById(R.id.et_theme);
//        mContacts = findViewById(R.id.tv_contacts);
        CheckBox checkBox1 = findViewById(R.id.radio1);
        CheckBox checkBox2 = findViewById(R.id.radio2);
        radios.add(checkBox1);
        radios.add(checkBox2);

        mRecyclerView = findViewById(R.id.photosView);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        photos.add(add);
        mAdapter = new FeekEditAdapter(photos);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String str = adapter.getData().get(position).toString();
                if (add.equals(str)) {
                    getPhotos();
                } else {
//                    showToast("onItemClick");
                    ArrayList<String> list = new ArrayList<>();
                    list.addAll(adapter.getData());
                    if (add.equals(list.get(list.size() - 1))) {
                        list.remove(list.size() - 1);
                    }
                    Bundle bundle = new Bundle();
                    bundle.putInt("currentPostion", position);
                    bundle.putStringArrayList("imageData", list);
                    PhotoDialog photoDialog = new PhotoDialog();
                    photoDialog.setArguments(bundle);
                    photoDialog.show(getSupportFragmentManager(), "");
                }
            }
        });

        mAdapter.setOnItemLongClickListener(new FeekEditAdapter.OnItemLongClickListener() {
                                                @Override
                                                public boolean onItemLongClick(BaseQuickAdapter adapter, XPopup.Builder builder, View view, int position) {
                                                    builder.asAttachList(new String[]{"删除"}, null,
                                                            new OnSelectListener() {
                                                                @Override
                                                                public void onSelect(int pos, String text) {
                                                                    adapter.remove(position);
                                                                    String str = adapter.getData().get(adapter.getData().size() - 1).toString();
                                                                    if (!add.equals(str)) {
                                                                        adapter.addData(adapter.getData().size(), add);
                                                                    }
                                                                }
                                                            }).show();
                                                    return true;
                                                }
                                            }
        );
    }

    @Override
    protected void initData() {
        userId = SpUtils.readInt(this, "userId", 0);
        getHttpData();
        initPicker();
    }

    public void changeRadios(View view) {
        CheckBox checkBox = (CheckBox) view;
        CommonUtil.unCheck(radios);
        checkBox.setChecked(true);
        // 显示选中项值
        checkBoxV = CommonUtil.getOne(radios);
    }

    /**
     * 选择器初始化
     */
    private void initPicker() {
        /**
         *反馈类型选择器
         */
        typePicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mType.setText(typeList.get(options1));
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(14)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(18)//滚轮文字大小
                .setCyclic(false, false, false)//循环与否
                .build();
        /**
         *部门人员选择器 todo
         */
//        contactsPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                //返回的分别是三个级别的选中位置
//                String tx = departList.get(options1) + "/"
//                        + staffList.get(options1).get(options2);
//
//                departOid = depList.get(options1).getOid();
//                userOid = depList.get(options1).getUserList().get(options2).getUserId();
//                mContacts.setText(tx);
//            }
//        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
//            @Override
//            public void onOptionsSelectChanged(int options1, int options2, int options3) {
//                if (options1 != FeekEditActivity.this.options) {
//                    FeekEditActivity.this.options = options1;
//                    FeekEditActivity.this.contactsPicker.setSelectOptions(options1, 0);
//                }
//            }
//        })
//                .setSubmitText("确定")//确定按钮文字
//                .setCancelText("取消")//取消按钮文字
//                .setSubCalSize(14)//确定和取消文字大小
//                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
//                .setCancelColor(Color.GRAY)//取消按钮文字颜色
//                .setContentTextSize(18)//滚轮文字大小
//                .setSelectOptions(0, 0)
//                .setCyclic(false, false, false)//循环与否
//                .build();


        /**
         * 模块页面选择器
         */
        mPagePicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mModular.setText(modelList.get(options1) + "/" + pageList.get(options1).get(options2));
                modularName = modulePageList.get(options1).getOid();
                pageName = modulePageList.get(options1).getAuthorityList().get(options2).getYeOid();
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                if (options1 != FeekEditActivity.this.modelOptions) {
                    FeekEditActivity.this.modelOptions = options1;
                    FeekEditActivity.this.mPagePicker.setSelectOptions(options1, 0);
                }
            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(14)//确定和取消文字大小
                .setSubmitColor(Color.GRAY)//确定按钮文字颜色
                .setCancelColor(Color.GRAY)//取消按钮文字颜色
                .setContentTextSize(18)//滚轮文字大小
                .setSelectOptions(0, 0)
                .setCyclic(false, false, false)//循环与否
                .build();
    }


    private void getHttpData() {
        OkGoUtils.getInstance().post(this, URL.FEED_BACK_TYPE_URL, null, 0, false, mCallback);
//        OkGoUtils.getInstance().post(this, URL.DEPARTMENT_GET, null, 1, false, mCallback);     //todo  部门人员选择功能
        OkGoUtils.getInstance().post(this, URL.GET_MODULE_PAGE, null, 2, false, mCallback);
    }

    private MyCallback mCallback = new MyCallback() {
        @Override
        public void onSuccess(ResponseBean response, int id) {
            if (response.getCode() == 200) {
                String data = response.getDataInfo().toString();
                switch (id) {
                    case 0:
                        FeedbackTypeBean typeBean = JSON.parseObject(data, FeedbackTypeBean.class);
                        typeList = typeBean.getDataList();
                        break;
//                    case 1:      //todo  部门人员选择功能
//                        depList = JSON.parseArray(data, DepartmentBean.class);
//                        departList.clear();
//                        staffList.clear();
//                        for (int i = 0; i < depList.size(); i++) {
//                            List<DepartmentBean.UserListBean> userList = depList.get(i).getUserList();
//                            ArrayList<String> list = new ArrayList<>();
//                            for (int j = 0; j < userList.size(); j++) {
//                                list.add(userList.get(j).getUserName());
//                            }
//                            departList.add(depList.get(i).getDepartName());
//                            staffList.add(list);
//                        }
//                        break;
                    case 2:
                        modulePageList = JSON.parseArray(data, ModulePageBean.class);

                        for (int i = 0; i < modulePageList.size(); i++) {
                            List<String> list = new ArrayList<>();
                            List<ModulePageBean.AuthorityListBean> listBeans = modulePageList.get(i).getAuthorityList();
                            for (int j = 0; j < listBeans.size(); j++) {
                                list.add(listBeans.get(j).getYeTitle());
                            }
                            pageList.add(list);
                            modelList.add(modulePageList.get(i).getTitle());
                        }
                        break;
                    case 5:
                        showToast("提交成功！");
                        finish();
                        break;
                }
            } else {
                showToast(response.getMsg());
            }
        }

        @Override
        public void onError(Throwable e, int id) {

        }
    };

    public void onItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_modular:
                if (ObjectUtils.notEmpty(modelList) && ObjectUtils.notEmpty(pageList)) {
                    mPagePicker.setPicker(modelList, pageList);
                    mPagePicker.show();
                }
                break;
            case R.id.item_type://添加反馈类型数据源
                if (ObjectUtils.notEmpty(typeList)) {
                    typePicker.setPicker(typeList);
                    typePicker.show();
                }
                break;
            // TODO: 2020/3/14
//            case R.id.item_contacts://添加部门人员数据源
//                if (ObjectUtils.notEmpty(departList) && ObjectUtils.notEmpty(staffList)) {
//                    contactsPicker.setPicker(departList, staffList);
//                    contactsPicker.show();
//                }
//                break;
            case R.id.button://
                submit();
                break;
        }
    }


    private void getPhotos() {
        int n = photoNum - (photos.size() - 1);
        if (n > 0) {
            EasyPhotos.createAlbum(FeekEditActivity.this, true, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                    .setFileProviderAuthority("com.nand.library.base")//参数说明：见下方`FileProvider的配置`
                    .setCount(n)//参数说明：最大可选数，默认1
                    .start(requestCode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestCode && resultCode == RESULT_OK) {
            //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
            ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
            for (Photo photo : resultPhotos) {
                mAdapter.addData(mAdapter.getData().size() - 1, photo.path);
            }
            if (mAdapter.getData().size() - 1 >= photoNum) {
                mAdapter.remove(mAdapter.getData().size() - 1);
            }
        }
    }


    public void submit() {
        String theme = mTheme.getText().toString().trim();
        String describe = mDescribe.getText().toString().trim();
        String modular = mModular.getText().toString();
        String type = mType.getText().toString();
//        String contacts = mContacts.getText().toString(); // ObjectUtils.isEmpty(contacts) ||
        if (ObjectUtils.isEmpty(theme) || ObjectUtils.isEmpty(describe) || ObjectUtils.isEmpty(modular) ||
                ObjectUtils.isEmpty(type) || ObjectUtils.isEmpty(checkBoxV)) {
            showToast("请完成信息");
            return;
        }

        HttpParams params = new HttpParams();
        params.put("fMmDepartmentOid", "3");
        params.put("fMmUserOid", "36");
        params.put("moduleTitle", modularName);
        params.put("pageTitle", pageName);
        params.put("title", theme);
        params.put("type", checkBoxV);
        params.put("description", describe);
        params.put("feedbackType", type);
        params.put("userId", userId);

        List<String> data = mAdapter.getData();
        //是否添加有图片
        if (data.size() > 1) {
            List<File> files = new ArrayList<>();
            for (String photo : data) {
                if (!photo.equals(add)) {
                    File file = new File(photo);
                    files.add(file);
                }
            }
            //上传图片
            OkGoUtils.getInstance().upload(this, com.nand.module.function.constant.URL.UPLOAD_PICTURES, files, new MyCallback() {
                @Override
                public void onSuccess(ResponseBean response, int id) {
                    String imagePath = "";
                    if (response.getCode() == 200) {
                        List<String> list = JSON.parseArray(response.getDataInfo().toString(), String.class);
                        for (int i = 0; i < list.size(); i++) {
                            if (i == list.size() - 1) {
                                imagePath += list.get(i);
                            } else {
                                imagePath += list.get(i) + ",";
                            }
                        }
                        params.put("attachment1", imagePath);
                        OkGoUtils.getInstance().post(FeekEditActivity.this, URL.FEEDBACK_ADD, params, 5, false, mCallback);
                    } else {
                        showToast(response.getMsg());
                    }
                }

                @Override
                public void onError(Throwable e, int id) {

                }
            });
        } else {
            OkGoUtils.getInstance().post(FeekEditActivity.this, URL.FEEDBACK_ADD, params, 5, false, mCallback);
        }
    }


    // 点击非输入框位置优先隐藏软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            pendingCollapseKeyword = isShouldHideInput(ev);
            if (pendingCollapseKeyword) focusedView = getCurrentFocus();
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            if (pendingCollapseKeyword) {
                hideInputMethod(this);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideInput(MotionEvent event) {

        View v = getCurrentFocus();
        if (v instanceof EditText) {
            int[] location = {0, 0};
            v.getLocationInWindow(location);
            return event.getX() < location[0]
                    || event.getX() > location[0] + v.getWidth()
                    || event.getY() < location[1]
                    || event.getY() > location[1] + v.getHeight();
        }
        return false;
    }

    // 抬起手指时如果焦点还在原来的EditText则收起键盘
    private void hideInputMethod(Context context) {

        View v = getCurrentFocus();
        if (v == focusedView) {
            focusedView.clearFocus();
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(focusedView.getWindowToken(), 0);
            }
        }
    }
}
